package com.android.functionmanagement.request.http;

import java.io.File;
import java.io.InputStream;
import java.util.HashMap;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.StringEntity;
import org.json.JSONObject;

import com.android.functionmanagement.globle.ConstantGloble;
import com.android.functionmanagement.globle.LogGloble;

import android.content.Context;


/**
 * 负责版本更新部分的http请求和资源数据不存在时向服务器请求数据 要求异步请求和同步请求，返回请求的数据 可以设置头部信息
 */
public class HttpEngine extends BaseHttpEngine {

	private static final String TAG = "HttpEngine"; 

	/**
	 * @param url
	 *            发送通信的地址
	 * @param method
	 *            GET POST 代表当前发送的是get或者post请求
	 * @param context
	 * @param nameValuePairs
	 *            POST 请求上送服务器的键值对
	 */
	public HashMap<String, Object> httpSend(String url, String method,
			Context context, JSONObject json,HashMap<String, Object> headerArg,File file)
			throws Exception {
		HashMap<String, Object> result = new HashMap<String, Object>();
		try {
			LogGloble.w(TAG,  "HttpEngine " + this.hashCode() + " httpSend  url= "+ url +" start");
			LogGloble.i(TAG, "httpSend url:" + url);
			LogGloble.i(TAG, "httpSend nameValuePairs:" + json);

			// result.put(ConstantGloble.HTTP_OBSERVER, ob);
			HttpResponse response = null;// 通讯响应对象

			// 根据请求方式post/get不同走不同方式
			if (ConstantGloble.GO_METHOD_GET.equals(method)) {// 如果method为get
				// 添加http参数到url
				String paramUrl = addParamsToHttpUrl(url, json);
				// 实例化一个HttpGet对象的实例
				httpGet = new HttpGet(paramUrl);
				httpGet.setHeader(ConstantGloble.USER_AGENT, getUserAgent());
				/*String cookie = ControlCenter.getInstanse(context).getCookie();
				if (!StringUtil.isNullOrEmpty(cookie)) {
					LogGloble.i(ConstantGloble.COOKIE, ConstantGloble.COOKIE
							+ ": " + cookie);
					httpGet.setHeader(ConstantGloble.COOKIE, cookie);
				}*/
				// 执行通讯，获得返回对象
				response = execute(httpGet, context);
			} else if (ConstantGloble.GO_METHOD_POST.equals(method)
					|| "".equals(method) || method == null) {
				// 如果method为post，就实例化一个HttpPost对象的实例，并把相应的请求参数封装进去
				
				httppost = new HttpPost(url);
				httppost.setHeader(ConstantGloble.USER_AGENT, getUserAgent());
				if (json == null && headerArg == null) {
					json = new JSONObject();
				}
				
				if(file != null){
					if(headerArg!= null)
						for (String key : headerArg.keySet()) {
							httppost.addHeader(key,""+headerArg.get(key));
						}
					FileEntity fileEntity = new FileEntity(file, "multipart/mixed");
			        httppost.setEntity(fileEntity);
				} else {
					StringEntity s = new StringEntity(json.toString());
					s.setContentEncoding("UTF-8");
					s.setContentType("application/json");
					httppost.setEntity(s);
				}

				/*httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,
						ConstantGloble.DEFAULT_ENCODE));*/
				/*String cookie = ControlCenter.getInstanse(context).getCookie();
				if (!StringUtil.isNullOrEmpty(cookie)) {
					LogGloble.i(ConstantGloble.COOKIE, ConstantGloble.COOKIE
							+ ": " + cookie);
					httppost.setHeader(ConstantGloble.COOKIE, cookie);
				}*/
				// 执行请求
				response = execute(httppost, context);
			}

			int reCode = 0;
			try {
				reCode = response.getStatusLine().getStatusCode();
				result.put(ConstantGloble.HTTP_RESPOSE_CODE, reCode);
			} catch (Exception e) {
				result.put(ConstantGloble.HTTP_RESPOSE_CODE, 500);
				return result;
			}
			Header[] headers = response.getAllHeaders();
			LogGloble.i(TAG, "------  Headers log Start ------------");
			for (int i = 0; i < headers.length; i++) {
				Header header = headers[i];
				LogGloble.i("Header ",
						header.getName() + "=" + header.getValue());
				if (header.getName().equals("Set-Cookie")) {
					//xxx.setCookie(header.getValue());
				}
			}
			LogGloble.i(TAG, "------  Headers log end  ------------");
			if (reCode == HttpStatus.SC_OK) {
				// 获取响应的实体流
				// 处理数据
				InputStream is = response.getEntity().getContent();
				try {
					String stringContent = inputStream2String(is);
					LogGloble.i(TAG, "stringContent:" + stringContent);
					// 处理数据
					is.close();
					result.put(ConstantGloble.HTTP_RESPOSE_CONTENT,
							stringContent);
				} finally {
					if (is != null) {
						is.close();
					}
				}
			}

			return result;
		} catch (Exception e) {
			LogGloble.w(TAG, "通信異常", e);
			result.put(ConstantGloble.HTTP_RESPOSE_CODE, 500);
			return result;
		} finally {
			LogGloble.w(TAG, "HttpEngine " + this.hashCode() + " httpSend url= "+ url +" end");
		}
	}


}
